<template>
    <div class="add-module">
        <line-head-form class="head" title="新增试卷模版" type="add" />
        <div v-for="(item,i) in moduleList" class="module-body" @mouseover="item.isHover=true" @mouseout="item.isHover=false" :key="i">
            <div class="module-head">
                <el-col :span="3">
                    <span class="add-require">模块：{{i+1 | SectionToChinese}}</span>
                </el-col>
                <el-col :span="7">
                    <span class="add-require">题型：</span>
                    <el-select :disabled="isView" placeholder="题型" v-model="item.dataQuestionType" @change="typeChange(i)">
                        <el-option v-for="(qType,qI) in condition.questionTypeList" :label="qType.name" :value="qType.id"></el-option>
                    </el-select>
                </el-col>
                <el-col :span="7">
                    <span class="add-require">题目数：</span>
                    <el-input :disabled="isView" type="number" v-model="item.qNum" @blur="setNoList(i)"></el-input>
                </el-col>
                <el-col :span="7">
                    <span>每题分值：</span>
                    <el-input :disabled="isView" v-model="item.average" @blur="setScore(i,item)"></el-input>
                </el-col>
            </div>
            <div class="module">
                <div class="module-item">
                    <div class="item-head" v-if="item.examModelQuesList.length">
                        <span class="m-name-input">{{item.dataQuestionType | showType(condition.questionTypeList)}}</span>
                        <span class="head-right">
                            <span class="all-num">总题目数 :
                                <em>{{item.qNum}}</em> 道</span>
                            <span class="all-score">总分 :
                                <em>{{itemScores[i] | formatNumber(2)}}</em> 分</span>
                        </span>
                    </div>
                    <div class="drag-head" v-if="item.examModelQuesList.length">
                        <div class="timu">题目</div>
                        <div class="tixing">题型</div>
                        <div class="zongfen">总分</div>
                        <div class="nanyi">难易度</div>
                        <div class="hexin">知识板块</div>
                        <div class="xiangxi">详细知识点</div>
                        <div class="remark">备注</div>
                        <div class="caozuo"></div>
                        <div class="line"></div>
                    </div>
                    <draggable v-model="item.examModelQuesList" @end="onEnd" class="drag-list">
                        <div class="d-item" v-for="(element,eI) in item.examModelQuesList" :key="eI">
                            <div class="timu">
                                <span>{{name[i][eI]}}</span>
                            </div>
                            <div class="tixing">{{element.dataQuestionType | showType(condition.questionTypeList)}}</div>
                            <div class="zongfen">
                                <el-input draggable="false" type="number" :disabled="isView" v-model="element.score" @blur="scoreBlur(element)"></el-input>
                            </div>
                            <div class="nanyi">
                                <el-rate :disabled="isView" v-model="element.hard" void-color="#fed44a" show-text :texts="['易','易','中','难','难']"></el-rate>
                            </div>
                            <div class="hexin">
                                <el-input :disabled="isView" v-model="element.knowledgeI" placeholder="多个请用 ；分开"></el-input>
                            </div>
                            <div class="xiangxi">
                                <el-input :disabled="isView" v-model="element.knowledgeD" placeholder="输入详细知识点"></el-input>
                            </div>
                            <div class="remark">
                                <el-input :disabled="isView" v-model="element.remark" placeholder="最多50字"></el-input>
                            </div>
                            <div class="caozuo" v-if="!isView">
                                <span @click="addItem(i,eI)">+</span>
                                <span @click="cutItem(i,eI)">-</span>
                            </div>
                        </div>
                    </draggable>
                </div>
                <div class="m-caozuo" v-if="!isView">
                    <el-button v-show="item.isHover" type="primary" class="height-btn" @click="addModule(i)">增加模块</el-button>
                    <el-button v-show="item.isHover" class="light-btn" @click="removeModule(i)">删除模块</el-button>
                </div>
            </div>
        </div>
        <div class="all-body">当前配置
            <em>{{allScore | formatNumber(2)}}</em>分 ; 总题目数
            <em>{{allNum||0}}</em>
        </div>
        <div class="m-next-btn">
            <el-button :disabled="isView" type="primary" class="height-btn" @click="saveModule">确定</el-button>
            <el-button class="light-btn" @click="$router.go(-1)">取消</el-button>
        </div>
    </div>
</template>
<script>
import draggable from 'vuedraggable'
import LineHeadForm from '../common/LineHeadForm'
import io from '../../lib/io'
import { mapState, mapActions, mapGetters } from 'vuex'
export default {
    name: 'add-module',
    components: {
        draggable,
        LineHeadForm
    },
    data() {
        return {
            isView: this.$route.query.isView === 'isView',
            activeId: this.$route.query.activeId,
            activeName: this.$route.query.activeName,
            id: this.$route.query.id,
            rangeType: this.$route.query.rangeType,
            moduleList: [{ isHover: false, qNum: 0, dataQuestionType: '', sort: 1, average: '', examModelQuesList: [] }],
            oldModuleList: [{ isHover: false, qNum: 0, dataQuestionType: '', sort: 1, average: '', examModelQuesList: [] }],
            addForm: {
                name: '1',
                sort: 1,
                dataQuestionType: '',
                score: 0,
                hard: 0,
                knowledgeD: '',
                knowledgeI: '',
                remark:''
            },
            itemScores: [],
            allNum: 0,
            allScore: 0,
            sort: [],
            name:[]
        }
    },
    filters: {
        showType(num, list) {
            let typeName = ''
            list.map((item, i) => {
                if (item.id === num) {
                    typeName = item.name
                }
            })
            return typeName
        }
    },
    watch: {
        'exam.examBlock'(val) {
            if (!val.length) {
                return
            }
            val.map((item, i) => {
                item.isHover = false
                item.qNum = item.examModelQuesList.length
            })
            this.moduleList = JSON.parse(JSON.stringify(val))
            this.oldModuleList = JSON.parse(JSON.stringify(val))
        },
        moduleList: {
            handler: function(val) {
                this.allNum = 0
                this.allScore = 0
                let itemNo = 1
                let nameNo=1
                val.map((item, i) => {
                    let itemScore = 0
                    this.sort[i] = []
                    this.name[i] = []
                    if (item.dataQuestionType === '107') {
                        let listNo = 1
                        item.examModelQuesList.map((eItem, eI) => {
                            itemScore += Number(eItem.score)
                            this.name[i].push(nameNo + '-' + listNo)
                            eItem.name=nameNo + '-' + listNo
                            listNo++
                            //排序
                            this.sort[i].push(itemNo)
                            itemNo++
                        })
                        nameNo++
                    } else {
                        item.examModelQuesList.map((eItem, eI) => {
                            itemScore += Number(eItem.score)
                            this.name[i].push(nameNo)
                            eItem.name=nameNo
                            nameNo++
                            //排序
                            this.sort[i].push(itemNo)
                            itemNo++
                        })
                    }
                    if (this.itemScores[i] === undefined) {
                        this.itemScores.push(itemScore)
                    } else {
                        this.itemScores.splice(i, 1, itemScore)
                    }
                    this.allScore += itemScore
                    this.allNum += Number(item.qNum)
                })
            },
            deep: true
        }
    },
    computed: {
        ...mapState(['condition', 'exam']),
    },
    created() {
        this.findQuestionTypeData()
        this.examModelBlockList({ examModelId: this.id })
        this.detailExamModel({ id: this.id })
    },
    methods: {
        ...mapActions(['findQuestionTypeData', 'examModelBlockList', 'detailExamModel']),
        onEnd() {

        },
        // setFocus(e){
        //     console.log(document.getElementById(e.target.id))
        //     document.getElementById(e.target.id).focus()
        // },
        // calcTotal(){
        //     this.moduleList.map((item,i)=>{
        //         let itemScore=0
        //         item.examModelQuesList.map((eItem,eI)=>{
        //             itemScore+=eItem.score
        //         })
        //         item.itemScore=itemScore
        //     })
        // },
        scoreBlur(element){
            if(element.score<0){
                this.$message('分数不能小于0')
                element.score=''
                return
            }
        },
        addItem(index, eIndex) {
            this.moduleList[index].examModelQuesList.splice(eIndex + 1, 0, { ...this.addForm, sort: eIndex + 2, score: this.moduleList[index].average, dataQuestionType: this.moduleList[index].dataQuestionType })
            this.moduleList[index].qNum++
            this.oldModuleList = JSON.parse(JSON.stringify(this.moduleList))
        },
        cutItem(index, eIndex) {
            this.moduleList[index].examModelQuesList.splice(eIndex, 1)
            this.moduleList[index].qNum--
            this.oldModuleList = JSON.parse(JSON.stringify(this.moduleList))
        },
        addModule(index) {
            this.moduleList.splice(index + 1, 0, { isHover: false, qNum: 0, dataQuestionType: '', sort: index + 2, average: '', examModelQuesList: [] })
            this.oldModuleList = JSON.parse(JSON.stringify(this.moduleList))
        },
        removeModule(index) {

            this.$confirm('是否确定删除该模块（模块下的小题将一起删除）').then(() => {
                this.moduleList.splice(index, 1)
            }).catch((err) => {
                console.log('取消')
            })
        },
        typeChange(index) {
            this.moduleList[index].examModelQuesList.map((item, i) => {
                item.dataQuestionType = this.moduleList[index].dataQuestionType
            })
        },
        setNoList(i) {
            if (this.moduleList[i].qNum < 1 || this.moduleList[i].qNum > 200) {
                this.$message('题目数的范围为0～200')
                return
            }
            let oldVal = this.oldModuleList
            let val = this.moduleList
            if (Number(val[i].qNum) > Number(oldVal[i].qNum)) {
                let no = val[i].qNum - oldVal[i].qNum
                for (let noI = 0; noI < no; noI++) {
                    val[i].examModelQuesList.push({ ...this.addForm, score: val[i].average, dataQuestionType: val[i].dataQuestionType })
                }
            } else if (Number(val[i].qNum) < Number(oldVal[i].qNum)) {
                let no = Number(oldVal[i].qNum) - Number(val[i].qNum)
                val[i].examModelQuesList.splice(val[i].examModelQuesList.length - no, no)
            }
            this.oldModuleList = JSON.parse(JSON.stringify(val))
        },
        setScore(i,item) {
            if(item.average<0){
                item.average=''
                this.$message('分数不能小于0')
                return
            }
            console.log(i,item)
            if (this.moduleList[i].average !== undefined) {
                this.moduleList[i].examModelQuesList.map(item => {
                    item.score = this.moduleList[i].average
                })
            }
        },
        sure() {
            let obj = { moduleName: this.addForm.moduleName, examModelQuesList: [] }
            for (let i = 0; i < this.addForm.allNum; i++) {
                obj.examModelQuesList.push({ dataQuestionType: this.addForm.dataQuestionType, average: this.addForm.average })
            }
            this.moduleList.push(obj)
        },
        async saveModule() {
            let typeIndex = 0
            let numIndex = 0
            let scoreIndex = 0
            let hardIndex = 0
            let xiangxiIndex = 0
            let hexinIndex = 0
            let xiangxiEmptyIndex = 0
            let hexinEmptyIndex = 0
            let remark = 0
            this.moduleList.map((item, i) => {
                item.examModelQuesList.map((eItem, eI) => {
                    eItem.sort = this.sort[i][eI]
                    if (!eItem.dataQuestionType) {
                        typeIndex = i + 1
                    }
                    if (!eItem.score) {
                        scoreIndex = i + 1
                    }
                    if (!eItem.hard) {
                        hardIndex = i + 1
                    }
                    if (!eItem.knowledgeD) {
                        xiangxiEmptyIndex = i + 1
                    }
                    if (!eItem.knowledgeI) {
                        hexinEmptyIndex = i + 1
                    }
                    if (eItem.knowledgeD.length > 40) {
                        xiangxiIndex = i + 1
                    }
                    if (eItem.knowledgeI.length > 40) {
                        hexinIndex = i + 1
                    }
                    if (eItem.remark&&eItem.remark.length > 50) {
                        remark = i + 1
                    }
                    //替换知识板块中文分号
                    eItem.knowledgeI = eItem.knowledgeI.replace(/；/g, ';')
                })
                if (!item.examModelQuesList.length) {
                    numIndex = i + 1
                }
            })
            if (numIndex > 0) {
                this.$message(`第${numIndex}个模块还未输入题目数`)
                return
            }
            if (typeIndex > 0) {
                this.$message(`第${typeIndex}个模块还未选择题型`)
                return
            }
            if (hardIndex > 0) {
                this.$message(`第${hardIndex}个模块还未选择难易度`)
                return
            }
            if (scoreIndex > 0) {
                this.$message(`第${scoreIndex}个模块还未输入分数`)
                return
            }
            if (xiangxiEmptyIndex > 0) {
                this.$message(`第${xiangxiEmptyIndex}个模块的详细知识点不能为空`)
                return
            }
            if (hexinEmptyIndex > 0) {
                this.$message(`第${hexinEmptyIndex}个模块的核心知识点不能为空`)
                return
            }
            if (xiangxiIndex > 0) {
                this.$message(`第${xiangxiIndex}个模块的详细知识点长度超过了40`)
                return
            }
            if (hexinIndex > 0) {
                this.$message(`第${hexinIndex}个模块的核心知识点长度超过了40`)
                return
            }
            if(remark>0){
                this.$message(`第${remark}个模块的备注长度超过了50`)
                return
            }
            let { data } = await io.post6(io.addBlock2ExamModel, { examModelId: this.id, examModelBlockAddJson: JSON.stringify(this.moduleList) })
            if (data.success) {
                this.$message({ type: 'success', message: '保存成功' })
                if (this.rangeType === 1) {
                    this.$router.push({ path: '/main/exam/set-use', query: { id: this.id, baseSectionId: this.exam.examDetail.baseSectionId, dataSubject: this.exam.examDetail.dataSubject, baseTrimesterId: this.exam.examDetail.baseTrimesterId, activeId: this.activeId, activeName: this.activeName } })
                } else {
                    this.$router.push({ path: '/main/exam/test-paper', query: { activeId: this.activeId, activeName: this.activeName } })
                }
            }
        }
    }
}
</script>

<style lang="stylus" scoped>
.add-module
    padding 10px 0 40px 0
    min-height 400px
    .el-select
        width 180px
    .module-body
        border 1px solid #e3e3e3
        margin-top 20px
        &:hover
            border-color #01cabf
    .module-head
        padding 10px 20px
        height 36px
        line-height 34px
        .el-input
            width 200px
.empty
    text-align center
    margin-top 100px
.add-require
    &:before
        content '*'
        color #f56c6c
        margin-right 5px
.item-head
    height 40px
    line-height 40px
    background #f7f7f7
    padding 0 20px
    font-size 14px
    margin-bottom 5px
    em
        font-style normal
        font-weight bold
        color #ff9000
    .all-num
        margin-right 15px
.m-name-input
    display inline-block
    width 200px
.head-right
    float right 
.module
    padding 0 0 20px 0
.m-next-btn
    text-align center
    margin-top 40px
.drag-head,.d-item
    text-align center
    background #f7f7f7
    height 50px
    line-height 50px
    position relative
    width 100%
    div
        display inline-block
        position relative
    .line
        position absolute
        bottom 0
        left 0
        height 3px
        width 100%
        background-image linear-gradient(90deg,#009fd7 0%,#01d1bb 100%)
    .timu
        width 3%
    .tixing
        width 6%
    .zongfen,.nanyi,.caozuo
        width 12%
    .xiangxi,.hexin,.remark
        width 16%
    .el-input
        width 80%
.all-body   
    font-size 16px
    color #333333
    text-align right 
    margin-top 15px
    em
        color #ff9000
        font-weight bold
        font-style normal
        margin 0 5px
        &:last-child
            margin-right 0
.d-item
    border-bottom 2px solid #ffffff
    .nanyi
        align-items center
        .el-rate
            font-size 20px
    .caozuo
        span
            cursor pointer
            display inline-block
            height 32px
            width 32px
            border solid 1px rgba(0, 177, 209, 0.2)
            background #fff
            font-size 30px
            color #00b1d1
            font-family 'MicrosoftYaHeiLight'
            line-height 32px
            text-align center
            margin 0px 10px
            border-radius 4px
            position relative
            top 6px
            &:last-child
                line-height 26px !important
                top 4px
.m-caozuo
    text-align center
    height 90px
    .el-button
        margin-top 30px
        background white !important
        border 1px solid #009ada
        color #009ada !important
        &.light-btn
            border 1px solid #01cabf
            color #01cabf !important
</style>
<style lang="stylus">
.add-module
    .el-dialog--center .el-dialog__body
        text-align center !important
</style>


